package de.jmda.gen.java.impl;

import org.apache.log4j.Logger;

import de.jmda.core.util.StringUtil;
import de.jmda.gen.GeneratorException;
import de.jmda.gen.java.DeclaredInstanceMethodGenerator;
import de.jmda.gen.java.MethodNameGenerator;
import de.jmda.gen.java.TypeNameGenerator;

/**
 * Allows upper case constructor method name (normal instance method names are
 * lower cased) and empty (<code>""</code>) return values.
 *
 * @author roger@jmda.de
 */
public class DefaultConstructorGenerator
    extends DefaultInstanceMethodGenerator
{
	private final static Logger LOGGER =
      Logger.getLogger(DefaultConstructorGenerator.class);

	public DefaultConstructorGenerator()
	{
		super();
	}

	public DefaultConstructorGenerator(DeclaredInstanceMethodGenerator generator)
	{
		super(generator);
	}

	/**
	 * Sets / replaces the method name generator with {@link
	 * DefaultConstructorNameGenerator} and thereby enables upper case constructor
	 * method name.
	 *
	 * @see de.jmda.gen.java.impl.AbstractMethodGenerator#setName(java.lang.String)
	 */
	@Override
  public void setName(String methodName)
  {
		MethodNameGenerator methodNameGenerator =
				new DefaultConstructorNameGenerator();
		
		methodNameGenerator.setMethodName(methodName);

		getDeclaredMethodGenerator().setMethodNameGenerator(methodNameGenerator);
  }

	/**
	 * makes sure that no return type for constructor will be generated
	 *
	 * @see de.jmda.gen.impl.AbstractCompoundGenerator#generate()
	 */
	@Override
  public StringBuffer generate() throws GeneratorException
  {
		TypeNameGenerator typeNameGenerator =
				getDeclaredMethodGenerator().getTypeNameGenerator();
		
		if (typeNameGenerator != null)
		{
			StringBuffer typename = typeNameGenerator.generate();

			if (false == StringUtil.isEmpty(typename))
			{
				LOGGER.warn(
						"constructor generator was configured to return " + typename + ", " +
						"return values are not allowed for constructors, " +
						"will modifiy type name generator accordingly");
				getDeclaredMethodGenerator().getTypeNameGenerator().setTypeName("");
			}
		}

		return super.generate();
  }
}